import streamlit as st
from llama_index.llms import OpenAI
import openai

api_key = "sk-Ifb2F6/yauxKx8OnRs2jA/lmymJzNCCEmIrJ+sgN+HanAgAA"
api_base = "https://api.app4gpt.com/v1"

st.set_page_config(page_title="ChatGPT", page_icon="🤖", layout="centered",
                   initial_sidebar_state="auto", menu_items=None)

st.title("chatGPT")
st.info(
    "[代码地址](https://gitee.com/WembleyPrince/chat-gpt.git)",
    icon="📃")

system_prompt = """
你是一位人工智能，假定你的名字叫chatGPT,
现在用户会向你提出一些问题，你需要耐心解答，
注意，大部分场景下都是中文场景，所以没有特殊情况请使用中文回答
"""
llm = OpenAI(model="gpt-4", temperature=0.1, system_prompt=system_prompt, api_key=api_key, api_base=api_base)

if "messages" not in st.session_state.keys():  # Initialize the chat messages history
    st.session_state.messages = [
        {"role": "assistant", "content": "你好!"}
    ]

if prompt := st.chat_input("Your question"):  # Prompt for user input and save to chat history
    st.session_state.messages.append({"role": "user", "content": prompt})

for message in st.session_state.messages:  # Display the prior chat messages
    with st.chat_message(message["role"]):
        st.write(message["content"])

# If last message is not from assistant, generate a new response
if st.session_state.messages[-1]["role"] != "assistant":
    with st.chat_message("assistant"):
        with st.spinner("Thinking..."):
            response = llm.complete(prompt)
            st.write(response.text)
            message = {"role": "assistant", "content": response.text}
            st.session_state.messages.append(message)  # Add response to message history
